package com.user.servlet;

import com.user.entity.BookInfo;
import com.user.entity.Page;
import com.user.service.IUserService;
import com.user.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "BookListServlet", value = "/BookListServlet")
public class BookListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        IUserService userService = new UserServiceImpl();
        int totalCount = userService.totalBookInfoCount();//数据总数

        //将分页所需的5个字段（其中有1个自动计算，因此实际只需要组装4个即可），组装到page对象之中
        Page page = new Page();

        String cPage = request.getParameter("currentPage");

        if (cPage == null) {
            cPage = "1";
        }

        int currentPage = Integer.parseInt(cPage);
        page.setCurrentPage(currentPage);
//		int currentPage = 2;//页码


        //注意 顺序
        //总数据数
        page.setTotalCount(totalCount);

		/* currentPage：当前页（页码）
	  	 students :当前页的数据集合（当前页的所有学生）

		*/

        int pageSize = 5;
        page.setPageSize(pageSize);
        if (request.getParameter("pageSize") != null) {
            pageSize = 5;
            page.setPageSize(pageSize);
        }


        List<BookInfo> BookList =
                userService.queryBookInfoByPage(currentPage, pageSize);

        //获得总页数
        int totalPage = page.getTotalPage();
        if (totalPage <= currentPage) {
            page.setCurrentPage(totalPage);
        }


        //包含学生数据
        page.setBookList(BookList);

        request.setAttribute("p", page);

        String adminname = request.getParameter("adminname");
        if (adminname != null)
            request.getRequestDispatcher("Admin/adminBooksList.jsp").forward(request, response);
        else
            request.getRequestDispatcher("User/userBooksList.jsp").forward(request, response);

    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
